package com.sunni.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration //表示 SpringSecurity的配置文件
@EnableWebSecurity //让Security配置生效
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//    制作角色组，，角色组内用户的账号、密码，，，角色组可以访问的页面(访问权限)
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
                .withUser("user").password(new MyPasswordEncoder().encode("000")).roles("USER") //设置USER用户组，并往里添加账户
                .and()
                .withUser("admin").password(new MyPasswordEncoder().encode("123")).roles("ADMIN","USER");
    }

//  (为页面) 设置权限，  逻辑：访问这个页面，需要哪个角色
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin").access("hasRole('ADMIN')")  // 设置/admin这个页面，需要哪个角色组的权限
                .antMatchers("/index").access("hasRole('USER') or hasRole('ADMIN')")
                .anyRequest().authenticated()   // 让上面的设置全部生效
                .and()
                .formLogin().loginPage("/login").permitAll()  //设置 /login 访问，失效(不使用Security自带的，用自定义的)
                .and()
                .logout().permitAll()
                .and()
                .csrf().disable();
    }
}
